"""
性能测试报告生成器 - 生成详细的HTML和PDF格式测试报告
"""
import json
import os
import base64
from datetime import datetime
from typing import Dict, Any, List
from pathlib import Path
import matplotlib.pyplot as plt
import seaborn as sns
import pandas as pd
from jinja2 import Template
import io

from utils.logger import Logger
from testing.performance_benchmark import PerformanceMetrics, TestConfiguration, SystemInfo

logger = get_logger("performance_report")


class PerformanceReportGenerator:
    """性能测试报告生成器"""
    
    def __init__(self):
        self.reports_dir = Path("reports/performance")
        self.reports_dir.mkdir(parents=True, exist_ok=True)
        
        # 设置matplotlib样式
        plt.style.use('seaborn-v0_8')
        sns.set_palette("husl")
    
    def generate_html_report(self, test_name: str, config: TestConfiguration, 
                           metrics: PerformanceMetrics, system_info: SystemInfo) -> str:
        """生成HTML格式的测试报告"""
        
        # 生成图表
        charts = self._generate_charts(metrics)
        
        # HTML模板
        html_template = """
        <!DOCTYPE html>
        <html lang="zh-CN">
        <head>
            <meta charset="UTF-8">
            <meta name="viewport" content="width=device-width, initial-scale=1.0">
            <title>MAESS 性能测试报告 - {{ test_name }}</title>
            <style>
                body {
                    font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
                    line-height: 1.6;
                    margin: 0;
                    padding: 20px;
                    background-color: #f5f5f5;
                }
                .container {
                    max-width: 1200px;
                    margin: 0 auto;
                    background: white;
                    padding: 30px;
                    border-radius: 10px;
                    box-shadow: 0 0 20px rgba(0,0,0,0.1);
                }
                .header {
                    text-align: center;
                    margin-bottom: 40px;
                    border-bottom: 3px solid #007acc;
                    padding-bottom: 20px;
                }
                .header h1 {
                    color: #007acc;
                    margin: 0;
                    font-size: 2.5em;
                }
                .header .subtitle {
                    color: #666;
                    font-size: 1.2em;
                    margin-top: 10px;
                }
                .section {
                    margin-bottom: 40px;
                }
                .section h2 {
                    color: #007acc;
                    border-left: 4px solid #007acc;
                    padding-left: 15px;
                    margin-bottom: 20px;
                }
                .metrics-grid {
                    display: grid;
                    grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
                    gap: 20px;
                    margin-bottom: 30px;
                }
                .metric-card {
                    background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
                    color: white;
                    padding: 20px;
                    border-radius: 10px;
                    text-align: center;
                    box-shadow: 0 4px 15px rgba(0,0,0,0.1);
                }
                .metric-card h3 {
                    margin: 0 0 10px 0;
                    font-size: 1.1em;
                    opacity: 0.9;
                }
                .metric-card .value {
                    font-size: 2em;
                    font-weight: bold;
                    margin: 0;
                }
                .metric-card .unit {
                    font-size: 0.9em;
                    opacity: 0.8;
                }
                .table-container {
                    overflow-x: auto;
                    margin-bottom: 30px;
                }
                table {
                    width: 100%;
                    border-collapse: collapse;
                    background: white;
                    border-radius: 8px;
                    overflow: hidden;
                    box-shadow: 0 2px 10px rgba(0,0,0,0.1);
                }
                th, td {
                    padding: 12px 15px;
                    text-align: left;
                    border-bottom: 1px solid #eee;
                }
                th {
                    background-color: #007acc;
                    color: white;
                    font-weight: 600;
                }
                tr:hover {
                    background-color: #f8f9fa;
                }
                .chart-container {
                    text-align: center;
                    margin: 30px 0;
                    padding: 20px;
                    background: white;
                    border-radius: 8px;
                    box-shadow: 0 2px 10px rgba(0,0,0,0.1);
                }
                .chart-title {
                    font-size: 1.3em;
                    color: #007acc;
                    margin-bottom: 20px;
                    font-weight: 600;
                }
                .chart-image {
                    max-width: 100%;
                    height: auto;
                    border-radius: 5px;
                }
                .status-good { color: #28a745; font-weight: bold; }
                .status-warning { color: #ffc107; font-weight: bold; }
                .status-error { color: #dc3545; font-weight: bold; }
                .recommendations {
                    background-color: #e7f3ff;
                    border-left: 4px solid #007acc;
                    padding: 20px;
                    border-radius: 5px;
                    margin-top: 20px;
                }
                .footer {
                    text-align: center;
                    margin-top: 50px;
                    padding-top: 20px;
                    border-top: 2px solid #eee;
                    color: #666;
                }
                .timestamp {
                    font-size: 0.9em;
                    color: #888;
                }
            </style>
        </head>
        <body>
            <div class="container">
                <!-- 报告头部 -->
                <div class="header">
                    <h1>MAESS 性能测试报告</h1>
                    <div class="subtitle">{{ test_name }}</div>
                    <div class="timestamp">生成时间: {{ current_time }}</div>
                </div>

                <!-- 关键指标概览 -->
                <div class="section">
                    <h2>关键性能指标</h2>
                    <div class="metrics-grid">
                        <div class="metric-card">
                            <h3>总请求数</h3>
                            <div class="value">{{ "{:,}".format(metrics.total_requests) }}</div>
                        </div>
                        <div class="metric-card">
                            <h3>成功率</h3>
                            <div class="value">{{ "{:.1f}".format((1 - metrics.error_rate) * 100) }}%</div>
                        </div>
                        <div class="metric-card">
                            <h3>平均响应时间</h3>
                            <div class="value">{{ "{:.0f}".format(metrics.mean_response_time) }}</div>
                            <div class="unit">毫秒</div>
                        </div>
                        <div class="metric-card">
                            <h3>P99响应时间</h3>
                            <div class="value">{{ "{:.0f}".format(metrics.p99_response_time) }}</div>
                            <div class="unit">毫秒</div>
                        </div>
                        <div class="metric-card">
                            <h3>吞吐量</h3>
                            <div class="value">{{ "{:.1f}".format(metrics.requests_per_second) }}</div>
                            <div class="unit">请求/秒</div>
                        </div>
                        <div class="metric-card">
                            <h3>错误率</h3>
                            <div class="value">{{ "{:.2f}".format(metrics.error_rate * 100) }}%</div>
                        </div>
                    </div>
                </div>

                <!-- 响应时间详细分析 -->
                <div class="section">
                    <h2>响应时间分析</h2>
                    <div class="table-container">
                        <table>
                            <thead>
                                <tr>
                                    <th>指标</th>
                                    <th>数值 (毫秒)</th>
                                    <th>状态</th>
                                </tr>
                            </thead>
                            <tbody>
                                <tr>
                                    <td>最小响应时间</td>
                                    <td>{{ "{:.2f}".format(metrics.min_response_time) }}</td>
                                    <td class="status-good">优秀</td>
                                </tr>
                                <tr>
                                    <td>平均响应时间</td>
                                    <td>{{ "{:.2f}".format(metrics.mean_response_time) }}</td>
                                    <td class="{{ 'status-good' if metrics.mean_response_time < 200 else 'status-warning' if metrics.mean_response_time < 500 else 'status-error' }}">
                                        {{ '优秀' if metrics.mean_response_time < 200 else '良好' if metrics.mean_response_time < 500 else '需优化' }}
                                    </td>
                                </tr>
                                <tr>
                                    <td>中位数响应时间</td>
                                    <td>{{ "{:.2f}".format(metrics.median_response_time) }}</td>
                                    <td class="{{ 'status-good' if metrics.median_response_time < 200 else 'status-warning' if metrics.median_response_time < 500 else 'status-error' }}">
                                        {{ '优秀' if metrics.median_response_time < 200 else '良好' if metrics.median_response_time < 500 else '需优化' }}
                                    </td>
                                </tr>
                                <tr>
                                    <td>P90响应时间</td>
                                    <td>{{ "{:.2f}".format(metrics.p90_response_time) }}</td>
                                    <td class="{{ 'status-good' if metrics.p90_response_time < 300 else 'status-warning' if metrics.p90_response_time < 800 else 'status-error' }}">
                                        {{ '优秀' if metrics.p90_response_time < 300 else '良好' if metrics.p90_response_time < 800 else '需优化' }}
                                    </td>
                                </tr>
                                <tr>
                                    <td>P95响应时间</td>
                                    <td>{{ "{:.2f}".format(metrics.p95_response_time) }}</td>
                                    <td class="{{ 'status-good' if metrics.p95_response_time < 400 else 'status-warning' if metrics.p95_response_time < 1000 else 'status-error' }}">
                                        {{ '优秀' if metrics.p95_response_time < 400 else '良好' if metrics.p95_response_time < 1000 else '需优化' }}
                                    </td>
                                </tr>
                                <tr>
                                    <td>P99响应时间</td>
                                    <td>{{ "{:.2f}".format(metrics.p99_response_time) }}</td>
                                    <td class="{{ 'status-good' if metrics.p99_response_time < 500 else 'status-warning' if metrics.p99_response_time < 1500 else 'status-error' }}">
                                        {{ '优秀' if metrics.p99_response_time < 500 else '良好' if metrics.p99_response_time < 1500 else '需优化' }}
                                    </td>
                                </tr>
                                <tr>
                                    <td>最大响应时间</td>
                                    <td>{{ "{:.2f}".format(metrics.max_response_time) }}</td>
                                    <td class="{{ 'status-good' if metrics.max_response_time < 1000 else 'status-warning' if metrics.max_response_time < 3000 else 'status-error' }}">
                                        {{ '优秀' if metrics.max_response_time < 1000 else '良好' if metrics.max_response_time < 3000 else '需优化' }}
                                    </td>
                                </tr>
                            </tbody>
                        </table>
                    </div>
                </div>

                <!-- 吞吐量分析 -->
                <div class="section">
                    <h2>吞吐量分析</h2>
                    <div class="table-container">
                        <table>
                            <thead>
                                <tr>
                                    <th>指标</th>
                                    <th>数值</th>
                                    <th>单位</th>
                                    <th>状态</th>
                                </tr>
                            </thead>
                            <tbody>
                                <tr>
                                    <td>请求吞吐量</td>
                                    <td>{{ "{:.2f}".format(metrics.requests_per_second) }}</td>
                                    <td>请求/秒</td>
                                    <td class="{{ 'status-good' if metrics.requests_per_second > 100 else 'status-warning' if metrics.requests_per_second > 50 else 'status-error' }}">
                                        {{ '优秀' if metrics.requests_per_second > 100 else '良好' if metrics.requests_per_second > 50 else '需优化' }}
                                    </td>
                                </tr>
                                <tr>
                                    <td>数据吞吐量</td>
                                    <td>{{ "{:.2f}".format(metrics.throughput_mb_per_second) }}</td>
                                    <td>MB/秒</td>
                                    <td class="status-good">正常</td>
                                </tr>
                            </tbody>
                        </table>
                    </div>
                </div>

                <!-- 错误分析 -->
                <div class="section">
                    <h2>错误分析</h2>
                    <div class="table-container">
                        <table>
                            <thead>
                                <tr>
                                    <th>错误类型</th>
                                    <th>数量</th>
                                    <th>占比</th>
                                    <th>状态</th>
                                </tr>
                            </thead>
                            <tbody>
                                <tr>
                                    <td>总错误数</td>
                                    <td>{{ "{:,}".format(metrics.failed_requests) }}</td>
                                    <td>{{ "{:.2f}".format(metrics.error_rate * 100) }}%</td>
                                    <td class="{{ 'status-good' if metrics.error_rate < 0.01 else 'status-warning' if metrics.error_rate < 0.05 else 'status-error' }}">
                                        {{ '优秀' if metrics.error_rate < 0.01 else '良好' if metrics.error_rate < 0.05 else '需优化' }}
                                    </td>
                                </tr>
                                <tr>
                                    <td>超时错误</td>
                                    <td>{{ "{:,}".format(metrics.timeout_requests) }}</td>
                                    <td>{{ "{:.2f}".format((metrics.timeout_requests / metrics.total_requests * 100) if metrics.total_requests > 0 else 0) }}%</td>
                                    <td class="{{ 'status-good' if (metrics.timeout_requests / metrics.total_requests) < 0.01 else 'status-warning' if (metrics.timeout_requests / metrics.total_requests) < 0.05 else 'status-error' }}">
                                        {{ '优秀' if (metrics.timeout_requests / metrics.total_requests) < 0.01 else '良好' if (metrics.timeout_requests / metrics.total_requests) < 0.05 else '需优化' }}
                                    </td>
                                </tr>
                            </tbody>
                        </table>
                    </div>
                </div>

                <!-- 资源使用分析 -->
                <div class="section">
                    <h2>资源使用分析</h2>
                    <div class="table-container">
                        <table>
                            <thead>
                                <tr>
                                    <th>资源类型</th>
                                    <th>平均使用</th>
                                    <th>峰值使用</th>
                                    <th>状态</th>
                                </tr>
                            </thead>
                            <tbody>
                                <tr>
                                    <td>CPU使用率</td>
                                    <td>{{ "{:.1f}".format(metrics.avg_cpu_usage) }}%</td>
                                    <td>{{ "{:.1f}".format(metrics.max_cpu_usage) }}%</td>
                                    <td class="{{ 'status-good' if metrics.max_cpu_usage < 70 else 'status-warning' if metrics.max_cpu_usage < 90 else 'status-error' }}">
                                        {{ '优秀' if metrics.max_cpu_usage < 70 else '良好' if metrics.max_cpu_usage < 90 else '需优化' }}
                                    </td>
                                </tr>
                                <tr>
                                    <td>内存使用</td>
                                    <td>{{ "{:.2f}".format(metrics.avg_memory_usage_gb) }} GB</td>
                                    <td>{{ "{:.2f}".format(metrics.max_memory_usage_gb) }} GB</td>
                                    <td class="status-good">正常</td>
                                </tr>
                            </tbody>
                        </table>
                    </div>
                </div>

                <!-- 测试配置信息 -->
                <div class="section">
                    <h2>测试配置</h2>
                    <div class="table-container">
                        <table>
                            <thead>
                                <tr>
                                    <th>配置项</th>
                                    <th>数值</th>
                                </tr>
                            </thead>
                            <tbody>
                                <tr>
                                    <td>测试名称</td>
                                    <td>{{ config.test_name }}</td>
                                </tr>
                                <tr>
                                    <td>并发用户数</td>
                                    <td>{{ "{:,}".format(config.concurrent_users) }}</td>
                                </tr>
                                <tr>
                                    <td>总请求数</td>
                                    <td>{{ "{:,}".format(config.total_requests) }}</td>
                                </tr>
                                <tr>
                                    <td>测试持续时间</td>
                                    <td>{{ config.test_duration }} 秒</td>
                                </tr>
                                <tr>
                                    <td>预热时间</td>
                                    <td>{{ config.warmup_duration }} 秒</td>
                                </tr>
                                <tr>
                                    <td>智能体类型</td>
                                    <td>{{ config.agent_type }}</td>
                                </tr>
                            </tbody>
                        </table>
                    </div>
                </div>

                <!-- 系统信息 -->
                <div class="section">
                    <h2>系统环境信息</h2>
                    <div class="table-container">
                        <table>
                            <thead>
                                <tr>
                                    <th>系统信息</th>
                                    <th>数值</th>
                                </tr>
                            </thead>
                            <tbody>
                                <tr>
                                    <td>CPU核心数</td>
                                    <td>{{ system_info.cpu_count }}</td>
                                </tr>
                                <tr>
                                    <td>CPU型号</td>
                                    <td>{{ system_info.cpu_model }}</td>
                                </tr>
                                <tr>
                                    <td>总内存</td>
                                    <td>{{ "{:.2f}".format(system_info.memory_total_gb) }} GB</td>
                                </tr>
                                <tr>
                                    <td>可用内存</td>
                                    <td>{{ "{:.2f}".format(system_info.memory_available_gb) }} GB</td>
                                </tr>
                                <tr>
                                    <td>总磁盘空间</td>
                                    <td>{{ "{:.2f}".format(system_info.disk_total_gb) }} GB</td>
                                </tr>
                                <tr>
                                    <td>可用磁盘空间</td>
                                    <td>{{ "{:.2f}".format(system_info.disk_available_gb) }} GB</td>
                                </tr>
                                <tr>
                                    <td>操作系统</td>
                                    <td>{{ system_info.os_name }} {{ system_info.os_version }}</td>
                                </tr>
                                <tr>
                                    <td>Python版本</td>
                                    <td>{{ system_info.python_version }}</td>
                                </tr>
                            </tbody>
                        </table>
                    </div>
                </div>

                <!-- 性能图表 -->
                {% if charts %}
                <div class="section">
                    <h2>性能图表</h2>
                    {% for chart in charts %}
                    <div class="chart-container">
                        <div class="chart-title">{{ chart.title }}</div>
                        <img src="data:image/png;base64,{{ chart.image_base64 }}" class="chart-image" alt="{{ chart.title }}">
                    </div>
                    {% endfor %}
                </div>
                {% endif %}

                <!-- 优化建议 -->
                <div class="section">
                    <h2>优化建议</h2>
                    <div class="recommendations">
                        <ul>
                        {% for recommendation in recommendations %}
                            <li>{{ recommendation }}</li>
                        {% endfor %}
                        </ul>
                    </div>
                </div>

                <!-- 报告尾部 -->
                <div class="footer">
                    <p>MAESS 智能体系统 - 性能测试报告</p>
                    <p class="timestamp">报告生成时间: {{ current_time }}</p>
                </div>
            </div>
        </body>
        </html>
        """
        
        # 渲染模板
        template = Template(html_template)
        
        # 计算推荐建议
        recommendations = self._generate_recommendations(metrics)
        
        html_content = template.render(
            test_name=test_name,
            current_time=datetime.now().strftime("%Y-%m-%d %H:%M:%S"),
            config=config,
            metrics=metrics,
            system_info=system_info,
            charts=charts,
            recommendations=recommendations
        )
        
        return html_content
    
    def _generate_charts(self, metrics: PerformanceMetrics) -> List[Dict[str, Any]]:
        """生成性能图表"""
        charts = []
        
        # 响应时间分布图
        chart1 = self._create_response_time_chart(metrics)
        if chart1:
            charts.append({
                'title': '响应时间分布',
                'image_base64': chart1
            })
        
        # 吞吐量趋势图
        chart2 = self._create_throughput_chart(metrics)
        if chart2:
            charts.append({
                'title': '吞吐量指标',
                'image_base64': chart2
            })
        
        return charts
    
    def _create_response_time_chart(self, metrics: PerformanceMetrics) -> str:
        """创建响应时间图表"""
        try:
            fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(15, 6))
            
            # 响应时间条形图
            response_times = [
                metrics.min_response_time,
                metrics.mean_response_time,
                metrics.median_response_time,
                metrics.p90_response_time,
                metrics.p95_response_time,
                metrics.p99_response_time,
                metrics.max_response_time
            ]
            
            labels = ['最小值', '平均值', '中位数', 'P90', 'P95', 'P99', '最大值']
            colors = ['#2ecc71', '#3498db', '#9b59b6', '#f39c12', '#e67e22', '#e74c3c', '#c0392b']
            
            bars = ax1.bar(labels, response_times, color=colors, alpha=0.8)
            ax1.set_title('响应时间指标', fontsize=14, fontweight='bold')
            ax1.set_ylabel('响应时间 (毫秒)')
            ax1.tick_params(axis='x', rotation=45)
            
            # 添加数值标签
            for bar, value in zip(bars, response_times):
                height = bar.get_height()
                ax1.text(bar.get_x() + bar.get_width()/2., height + height*0.01,
                        f'{value:.0f}', ha='center', va='bottom', fontweight='bold')
            
            # 性能等级饼图
            performance_categories = ['优秀', '良好', '需优化']
            performance_values = [
                sum(1 for rt in response_times if rt < 200),  # 优秀
                sum(1 for rt in response_times if 200 <= rt < 500),  # 良好
                sum(1 for rt in response_times if rt >= 500)   # 需优化
            ]
            
            colors_pie = ['#2ecc71', '#f39c12', '#e74c3c']
            ax2.pie(performance_values, labels=performance_categories, colors=colors_pie, 
                   autopct='%1.1f%%', startangle=90)
            ax2.set_title('响应时间性能分布', fontsize=14, fontweight='bold')
            
            plt.tight_layout()
            
            # 转换为base64
            buffer = io.BytesIO()
            plt.savefig(buffer, format='png', dpi=300, bbox_inches='tight')
            buffer.seek(0)
            image_base64 = base64.b64encode(buffer.getvalue()).decode()
            plt.close()
            
            return image_base64
            
        except Exception as e:
            logger.error(f"生成响应时间图表失败: {str(e)}")
            return ""
    
    def _create_throughput_chart(self, metrics: PerformanceMetrics) -> str:
        """创建吞吐量图表"""
        try:
            fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(15, 6))
            
            # 吞吐量指标
            throughput_data = [
                metrics.requests_per_second,
                metrics.throughput_mb_per_second * 10  # 放大10倍以便显示
            ]
            
            labels = ['请求吞吐量', '数据吞吐量 (×10)']
            colors = ['#3498db', '#2ecc71']
            
            bars = ax1.bar(labels, throughput_data, color=colors, alpha=0.8)
            ax1.set_title('系统吞吐量', fontsize=14, fontweight='bold')
            ax1.set_ylabel('数值')
            
            # 添加数值标签
            for bar, value in zip(bars, throughput_data):
                height = bar.get_height()
                ax1.text(bar.get_x() + bar.get_width()/2., height + height*0.01,
                        f'{value:.1f}', ha='center', va='bottom', fontweight='bold')
            
            # 成功率与错误率
            success_rate = (1 - metrics.error_rate) * 100
            error_rate = metrics.error_rate * 100
            
            categories = ['成功率', '错误率']
            values = [success_rate, error_rate]
            colors = ['#2ecc71', '#e74c3c']
            
            bars2 = ax2.bar(categories, values, color=colors, alpha=0.8)
            ax2.set_title('请求成功率分析', fontsize=14, fontweight='bold')
            ax2.set_ylabel('百分比 (%)')
            ax2.set_ylim(0, 100)
            
            # 添加数值标签
            for bar, value in zip(bars2, values):
                height = bar.get_height()
                ax2.text(bar.get_x() + bar.get_width()/2., height + 1,
                        f'{value:.1f}%', ha='center', va='bottom', fontweight='bold')
            
            plt.tight_layout()
            
            # 转换为base64
            buffer = io.BytesIO()
            plt.savefig(buffer, format='png', dpi=300, bbox_inches='tight')
            buffer.seek(0)
            image_base64 = base64.b64encode(buffer.getvalue()).decode()
            plt.close()
            
            return image_base64
            
        except Exception as e:
            logger.error(f"生成吞吐量图表失败: {str(e)}")
            return ""
    
    def _generate_recommendations(self, metrics: PerformanceMetrics) -> List[str]:
        """生成优化建议"""
        recommendations = []
        
        # 响应时间建议
        if metrics.p99_response_time > 1000:
            recommendations.append("🔴 高延迟警告：P99响应时间超过1秒，建议优化查询逻辑或增加缓存")
        elif metrics.p99_response_time > 500:
            recommendations.append("🟡 响应时间优化：P99响应时间超过500ms，建议检查慢查询")
        else:
            recommendations.append("🟢 响应时间良好：P99响应时间在合理范围内")
        
        # 错误率建议
        if metrics.error_rate > 0.05:
            recommendations.append("🔴 高错误率：错误率超过5%，需要立即调查错误原因")
        elif metrics.error_rate > 0.01:
            recommendations.append("🟡 错误率注意：错误率超过1%，建议增加错误监控和告警")
        else:
            recommendations.append("🟢 错误率优秀：错误率在可接受范围内")
        
        # 吞吐量建议
        if metrics.requests_per_second < 100:
            recommendations.append("🟡 吞吐量优化：吞吐量低于100请求/秒，建议优化并发处理")
        elif metrics.requests_per_second > 1000:
            recommendations.append("🟢 吞吐量优秀：系统处理能力强劲")
        else:
            recommendations.append("🟢 吞吐量良好：系统处理能力正常")
        
        # CPU使用建议
        if metrics.max_cpu_usage > 90:
            recommendations.append("🔴 CPU瓶颈：CPU使用率峰值超过90%，建议增加服务器资源")
        elif metrics.max_cpu_usage > 70:
            recommendations.append("🟡 CPU注意：CPU使用率峰值超过70%，建议监控负载趋势")
        else:
            recommendations.append("🟢 CPU使用健康：CPU使用率在合理范围内")
        
        # 通用建议
        recommendations.extend([
            "📊 建议定期运行性能测试，建立性能基线",
            "📈 建议设置性能监控告警，及时发现性能退化",
            "🔧 建议在高负载场景下进行压力测试验证"
        ])
        
        return recommendations
    
    def save_html_report(self, html_content: str, filename: str):
        """保存HTML报告"""
        try:
            filepath = self.reports_dir / filename
            with open(filepath, 'w', encoding='utf-8') as f:
                f.write(html_content)
            
            logger.info(f"HTML报告已保存: {filepath}")
            return str(filepath)
            
        except Exception as e:
            logger.error(f"保存HTML报告失败: {str(e)}")
            return None
    
    def generate_json_report(self, test_name: str, config: TestConfiguration,
                           metrics: PerformanceMetrics, system_info: SystemInfo) -> Dict[str, Any]:
        """生成JSON格式的详细报告"""
        
        report = {
            'metadata': {
                'report_version': '1.0',
                'generated_at': datetime.now().isoformat(),
                'test_name': test_name,
                'report_type': 'performance_benchmark'
            },
            'system_environment': {
                'hardware': {
                    'cpu_cores': system_info.cpu_count,
                    'cpu_model': system_info.cpu_model,
                    'total_memory_gb': round(system_info.memory_total_gb, 2),
                    'available_memory_gb': round(system_info.memory_available_gb, 2),
                    'total_disk_gb': round(system_info.disk_total_gb, 2),
                    'available_disk_gb': round(system_info.disk_available_gb, 2)
                },
                'software': {
                    'os_name': system_info.os_name,
                    'os_version': system_info.os_version,
                    'python_version': system_info.python_version
                }
            },
            'test_configuration': {
                'test_name': config.test_name,
                'concurrent_users': config.concurrent_users,
                'total_requests': config.total_requests,
                'ramp_up_time': config.ramp_up_time,
                'test_duration': config.test_duration,
                'warmup_duration': config.warmup_duration,
                'agent_type': config.agent_type,
                'request_payload': config.request_payload
            },
            'performance_metrics': {
                'request_metrics': {
                    'total_requests': metrics.total_requests,
                    'successful_requests': metrics.successful_requests,
                    'failed_requests': metrics.failed_requests,
                    'timeout_requests': metrics.timeout_requests,
                    'success_rate': round((1 - metrics.error_rate) * 100, 2),
                    'error_rate': round(metrics.error_rate * 100, 2)
                },
                'response_time_metrics': {
                    'min_ms': round(metrics.min_response_time, 2),
                    'mean_ms': round(metrics.mean_response_time, 2),
                    'median_ms': round(metrics.median_response_time, 2),
                    'p90_ms': round(metrics.p90_response_time, 2),
                    'p95_ms': round(metrics.p95_response_time, 2),
                    'p99_ms': round(metrics.p99_response_time, 2),
                    'max_ms': round(metrics.max_response_time, 2)
                },
                'throughput_metrics': {
                    'requests_per_second': round(metrics.requests_per_second, 2),
                    'throughput_mb_per_second': round(metrics.throughput_mb_per_second, 2)
                },
                'resource_usage': {
                    'avg_cpu_usage': round(metrics.avg_cpu_usage, 2),
                    'max_cpu_usage': round(metrics.max_cpu_usage, 2),
                    'avg_memory_usage_gb': round(metrics.avg_memory_usage_gb, 2),
                    'max_memory_usage_gb': round(metrics.max_memory_usage_gb, 2)
                },
                'test_timing': {
                    'start_time': metrics.test_start_time.isoformat(),
                    'end_time': metrics.test_end_time.isoformat(),
                    'duration_seconds': round((metrics.test_end_time - metrics.test_start_time).total_seconds(), 2)
                }
            },
            'performance_analysis': {
                'overall_grade': self._calculate_overall_grade(metrics),
                'performance_status': self._get_performance_status(metrics),
                'key_findings': self._generate_key_findings(metrics),
                'recommendations': self._generate_recommendations(metrics)
            }
        }
        
        return report
    
    def _calculate_overall_grade(self, metrics: PerformanceMetrics) -> str:
        """计算总体性能等级"""
        score = 0
        
        # 响应时间评分 (40%)
        if metrics.p99_response_time < 200:
            score += 40
        elif metrics.p99_response_time < 500:
            score += 30
        elif metrics.p99_response_time < 1000:
            score += 20
        else:
            score += 10
        
        # 错误率评分 (30%)
        if metrics.error_rate < 0.01:
            score += 30
        elif metrics.error_rate < 0.05:
            score += 20
        elif metrics.error_rate < 0.1:
            score += 10
        else:
            score += 5
        
        # 吞吐量评分 (20%)
        if metrics.requests_per_second > 1000:
            score += 20
        elif metrics.requests_per_second > 500:
            score += 15
        elif metrics.requests_per_second > 100:
            score += 10
        else:
            score += 5
        
        # 资源使用评分 (10%)
        if metrics.max_cpu_usage < 70:
            score += 10
        elif metrics.max_cpu_usage < 90:
            score += 7
        else:
            score += 3
        
        # 转换为等级
        if score >= 90:
            return "A+"
        elif score >= 80:
            return "A"
        elif score >= 70:
            return "B+"
        elif score >= 60:
            return "B"
        elif score >= 50:
            return "C"
        else:
            return "D"
    
    def _get_performance_status(self, metrics: PerformanceMetrics) -> str:
        """获取性能状态"""
        if metrics.p99_response_time < 500 and metrics.error_rate < 0.01 and metrics.max_cpu_usage < 70:
            return "优秀"
        elif metrics.p99_response_time < 1000 and metrics.error_rate < 0.05 and metrics.max_cpu_usage < 90:
            return "良好"
        else:
            return "需优化"
    
    def _generate_key_findings(self, metrics: PerformanceMetrics) -> List[str]:
        """生成关键发现"""
        findings = []
        
        # 响应时间发现
        if metrics.p99_response_time < 200:
            findings.append(f"✅ 响应时间表现优秀，P99为{metrics.p99_response_time:.0f}毫秒")
        elif metrics.p99_response_time > 1000:
            findings.append(f"⚠️ 响应时间需要关注，P99为{metrics.p99_response_time:.0f}毫秒")
        
        # 错误率发现
        if metrics.error_rate < 0.01:
            findings.append(f"✅ 错误率控制良好，仅为{metrics.error_rate*100:.2f}%")
        elif metrics.error_rate > 0.05:
            findings.append(f"⚠️ 错误率偏高，达到{metrics.error_rate*100:.2f}%")
        
        # 吞吐量发现
        if metrics.requests_per_second > 1000:
            findings.append(f"✅ 吞吐量表现强劲，达到{metrics.requests_per_second:.0f}请求/秒")
        elif metrics.requests_per_second < 100:
            findings.append(f"⚠️ 吞吐量偏低，仅为{metrics.requests_per_second:.0f}请求/秒")
        
        # 资源使用发现
        if metrics.max_cpu_usage > 90:
            findings.append(f"⚠️ CPU使用率达到{metrics.max_cpu_usage:.1f}%，可能存在瓶颈")
        elif metrics.max_cpu_usage < 50:
            findings.append(f"✅ CPU使用率健康，峰值仅为{metrics.max_cpu_usage:.1f}%")
        
        return findings
    
    def save_json_report(self, json_report: Dict[str, Any], filename: str):
        """保存JSON报告"""
        try:
            filepath = self.reports_dir / filename
            with open(filepath, 'w', encoding='utf-8') as f:
                json.dump(json_report, f, ensure_ascii=False, indent=2)
            
            logger.info(f"JSON报告已保存: {filepath}")
            return str(filepath)
            
        except Exception as e:
            logger.error(f"保存JSON报告失败: {str(e)}")
            return None


# 使用示例
async def generate_comprehensive_report(test_name: str, config: TestConfiguration,
                                      metrics: PerformanceMetrics, system_info: SystemInfo):
    """生成综合性能测试报告"""
    
    generator = PerformanceReportGenerator()
    
    # 生成HTML报告
    html_content = generator.generate_html_report(test_name, config, metrics, system_info)
    html_filepath = generator.save_html_report(html_content, f"{test_name}_report.html")
    
    # 生成JSON报告
    json_report = generator.generate_json_report(test_name, config, metrics, system_info)
    json_filepath = generator.save_json_report(json_report, f"{test_name}_report.json")
    
    logger.info(f"性能测试报告生成完成:")
    logger.info(f"  HTML报告: {html_filepath}")
    logger.info(f"  JSON报告: {json_filepath}")
    
    return {
        'html_report': html_filepath,
        'json_report': json_filepath,
        'report_summary': {
            'test_name': test_name,
            'overall_grade': generator._calculate_overall_grade(metrics),
            'performance_status': generator._get_performance_status(metrics),
            'key_metrics': {
                'p99_response_time': metrics.p99_response_time,
                'error_rate': metrics.error_rate,
                'requests_per_second': metrics.requests_per_second,
                'max_cpu_usage': metrics.max_cpu_usage
            }
        }
    }


if __name__ == "__main__":
    # 这里可以添加测试代码
    print("性能测试报告生成器已加载")
    print("使用 generate_comprehensive_report() 函数生成完整报告")